const fp = require('lodash/fp')

const cars = [
    {
        name: 'Ferrari FF',
        horsepower: 660,
        dollar_value: 700000,
        in_stock: true
    },
    {
        name: 'Spyker C12 Zagato',
        horsepower: 650,
        dollar_value: 648000,
        in_stock: false
    },
    {
        name: 'Jaguar XKR-S',
        horsepower: 550,
        dollar_value: 132000,
        in_stock: false
    },
    {
        name: 'Audi R8',
        horsepower: 525,
        dollar_value: 114200,
        in_stock: false
    },
    {
        name: 'Aston Martin One-77',
        horsepower:  750,
        dollar_value: 1850000,
        in_stock: true
    },
    {
        name: 'Pagani Huayra',
        horsepower: 700,
        dollar_value: 1300000,
        in_stock: false
    }
]

// 使用函数组合fp.flowRight()重新实现下面这个函数

let isLastInStock = function (cars) {
    let last_car = fp.last(cars)
    return fp.prop('in_stock', last_car)
}
const _ = require('lodash')
const curried = _.curry(fp.prop('in_stock'))
var r = fp.flowRight(curried, fp.last)
console.log(r(cars))


// 2. 使用fp.flowRight(), fp.prop(),fp.first()获取第一个car的name

const curried2 = _.curry(fp.prop('name'))
var v = fp.flowRight(curried2, fp.first)
console.log(v(cars))


//3 . 

let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs);
} // 无需改动

// let averageDollarValue = function (cars) {
//     let dollar_values = fp.map(function (car) {
//         return car.dollar_value
//     }, cars)
//     return _average(dollar_values)
// }

// averageDollarValue(cars)

// Step 1 获取车辆价格数组
// Step 2 求数组中所有元素平均值

let averageDollarValue2 = function (cars) {
   return fp.flowRight(_average, fp.map)(function (car) {
        return car.dollar_value
    }, cars);
}
console.log(averageDollarValue2(cars));

// 4. 使用flowright写一个sanitizeNames的函数，返回一个下划线连接的小写字符串，把数组中的name转换为这种形式：
// 如 sanitizeNames(["Hello World"]) => ["hello_world"]

let _underscore = fp.replace(/\W+/g, '_') //无需改动，并在新函数中使用它

var str = ' Hello World '

// step 1 toLowerCase
// step 2 _underscore

const sanitizeNames = function (name) {
    return fp.flowRight(_underscore, function (name) {
        return name.trim().toLowerCase()
    })(name)
}

sanitizeNames(str)
console.log(sanitizeNames(str))